<!--
 * @Descripttion: 数据表格组件
 * @version: 1.10
 * @Author: sakuya
 * @Date: 2021年11月29日21:51:15
 * @LastEditors: Xujianchen
 * @LastEditTime: 2023-03-17 10:22:40
-->

<template>
    <div ref="scTableMain" v-loading="loading" class="scTable" :style="{ height: _height }">
        <div class="scTable-table" :style="{ height: _table_height }">
            <el-table v-bind="$attrs" :key="toggleIndex" ref="scTable" :data="tableData" :row-key="rowKey"
                :height="height == 'auto' ? null : '100%'" :size="config.size" :border="config.border"
                :stripe="config.stripe" :summary-method="remoteSummary ? remoteSummaryMethod : summaryMethod"
                @sort-change="sortChange" @filter-change="filterChange">
                <slot></slot>
                <template v-for="(item, index) in userColumn" :key="index">
                    <el-table-column v-if="!item.hide" :column-key="item.prop" :label="item.label" :prop="item.prop"
                        :width="item.width" :sortable="item.sortable" :fixed="item.fixed" :filters="item.filters"
                        :filter-method="remoteFilter || !item.filters ? null : filterHandler"
                        :show-overflow-tooltip="item.showOverflowTooltip">
                        <template #default="scope">
                            <slot :name="item.prop" v-bind="scope">
                                {{ scope.row[item.prop] }}
                            </slot>
                        </template>
                    </el-table-column>
                </template>
                <el-table-column min-width="1"></el-table-column>
                <template #empty>
                    <el-empty :description="emptyText" :image-size="100"></el-empty>
                </template>
            </el-table>
        </div>
        <div v-if="!hidePagination || !hideDo" class="scTable-page">
            <div class="scTable-pagination">
                <el-pagination v-if="!hidePagination" v-model:currentPage="currentPage" background :small="true"
                    :layout="paginationLayout" :total="total" :page-size="scPageSize" :page-sizes="pageSizes"
                    @current-change="paginationChange" @update:page-size="pageSizeChange"></el-pagination>
            </div>
            <div v-if="!hideDo" class="scTable-do">
                <el-button v-if="!hideRefresh" icon="el-icon-refresh" circle style="margin-left: 15px"
                    @click="refresh"></el-button>
                <el-popover v-if="column" placement="top" title="列设置" :width="500" trigger="click" :hide-after="0"
                    @show="customColumnShow = true" @after-leave="customColumnShow = false">
                    <template #reference>
                        <el-button icon="el-icon-set-up" circle style="margin-left: 15px"></el-button>
                    </template>
                    <columnSetting v-if="customColumnShow" ref="columnSetting" :column="userColumn"
                        @userChange="columnSettingChange" @save="columnSettingSave" @back="columnSettingBack">
                    </columnSetting>
                </el-popover>
                <el-popover v-if="!hideSetting" placement="top" title="表格设置" :width="400" trigger="click"
                    :hide-after="0">
                    <template #reference>
                        <el-button icon="el-icon-setting" circle style="margin-left: 15px"></el-button>
                    </template>
                    <el-form label-width="80px" label-position="left">
                        <el-form-item label="表格尺寸">
                            <el-radio-group v-model="config.size" size="small" @change="configSizeChange">
                                <el-radio-button label="large">大</el-radio-button>
                                <el-radio-button label="default">正常</el-radio-button>
                                <el-radio-button label="small">小</el-radio-button>
                            </el-radio-group>
                        </el-form-item>
                        <el-form-item label="样式">
                            <el-checkbox v-model="config.border" label="纵向边框"></el-checkbox>
                            <el-checkbox v-model="config.stripe" label="斑马纹"></el-checkbox>
                        </el-form-item>
                    </el-form>
                </el-popover>
            </div>
        </div>
    </div>
</template>

<script lang="ts">
import { defineComponent, PropType } from 'vue'
import config from '@/config/table'
import columnSetting from './columnSetting.vue'

// 定义接口类型
interface ApiObj {
    get: (data: any) => Promise<any>
    post: (data: any) => Promise<any>
}

interface TableData {
    [key: string]: any
    total?: number
    rows?: any[]
    summary?: Record<string, any>
}

interface ColumnItem {
    [key: string]: any
}

interface SortParams {
    column?: any
    prop?: string | null
    order?: string | null
}

interface FilterParams {
    [key: string]: any
}

export default {
    name: 'wTable',
    components: {
        columnSetting
    },
    props: {
        tableName: { type: String,  required: false },
        apiObj: { type: Object as PropType<ApiObj>, default: () => ({}) },
        params: { type: Object as PropType<Record<string, any>>, default: () => ({}) },
        data: { type: Object as PropType<TableData>, default: () => ({}) },
        height: { type: [String, Number] as PropType<string | number>, default: '100%' },
        size: { type: String, default: 'default' },
        border: { type: Boolean, default: false },
        stripe: { type: Boolean, default: false },
        pageSize: { type: Number, default: config.pageSize },
        pageSizes: { type: Array as PropType<number[]>, default: () => config.pageSizes },
        rowKey: { type: String, default: '' },
        summaryMethod: { type: Function as PropType<(param: any) => any[]>, default: null },
        column: { type: Object as PropType<ColumnItem[]>, default: () => ([]) },
        remoteSort: { type: Boolean, default: false },
        remoteFilter: { type: Boolean, default: false },
        remoteSummary: { type: Boolean, default: false },
        hidePagination: { type: Boolean, default: false },
        hideDo: { type: Boolean, default: false },
        hideRefresh: { type: Boolean, default: false },
        hideSetting: { type: Boolean, default: false },
        paginationLayout: { type: String, default: config.paginationLayout }
    },
    watch: {
        data(newVal: TableData) {
            this.tableData = newVal
            this.total = this.tableData.total || 0
        },
        apiObj() {
            this.tableParams = this.params
            this.refresh()
        },
        loading(val: boolean) {
            this.changeloading(val)
        }
    },
    computed: {
        _height(): string {
            return Number(this.height) ? `${Number(this.height)}px` : this.height as string
        },
        _table_height(): string {
            return this.hidePagination && this.hideDo ? '100%' : 'calc(100% - 50px)'
        }
    },
    data() {
        return {
            scPageSize: this.pageSize,
            isActivat: true,
            emptyText: '暂无数据',
            toggleIndex: 0,
            tableData: [] as any[],
            total: 0,
            currentPage: 1,
            prop: null as string | null,
            order: null as string | null,
            loading: false,
            tableHeight: '100%',
            tableParams: this.params as Record<string, any>,
            userColumn: [] as ColumnItem[],
            customColumnShow: false,
            summary: {} as Record<string, any>,
            config: {
                size: this.size,
                border: this.border,
                stripe: this.stripe
            }
        }
    },
    mounted() {
        if (this.column) {
            this.getCustomColumn()
        } else {
            this.userColumn = this.column as ColumnItem[]
        }

        if (this.apiObj) {
            this.getData()
        } else if (this.data) {
            this.tableData = this.data.rows || this.data
            this.total = this.tableData.length
        }
    },
    activated() {
        if (!this.isActivat) {
            (this.$refs.scTable as any).doLayout()
        }
    },
    deactivated() {
        this.isActivat = false
    },
    methods: {
        async getCustomColumn() {
            const userColumn = await config.columnSettingGet(this.tableName, this.column)
            this.userColumn = userColumn
        },
        async getData() {
            this.loading = true
            const reqData: Record<string, any> = {
                [config.request.page]: this.currentPage,
                [config.request.pageSize]: this.scPageSize,
                [config.request.prop]: this.prop,
                [config.request.order]: this.order
            }

            if (this.hidePagination) {
                delete reqData[config.request.page]
                delete reqData[config.request.pageSize]
            }

            Object.assign(reqData, this.tableParams)

            let res: any
            try {
                if (this.apiObj.get !== undefined) {
                    res = await this.apiObj.get(reqData)
                } else {
                    const req = { data: reqData }
                    res = await this.apiObj.post!(req)
                }
            } catch (error: any) {
                this.loading = false
                this.emptyText = error.statusText || '请求失败'
                return false
            }

            let response: any
            try {
                response = config.parseData(res)
            } catch (error) {
                this.loading = false
                this.emptyText = '数据格式错误'
                return false
            }

            if (response.code !== config.successCode) {
                this.loading = false
                this.emptyText = response.msg || '请求错误'
            } else {
                this.emptyText = '暂无数据'
                if (this.hidePagination) {
                    this.tableData = response.data || []
                } else {
                    this.tableData = response.rows || []
                }
                this.total = response.total || 0
                this.summary = response.summary || {}
                this.loading = false
            }

            (this.$refs.scTable as any).setScrollTop(0)
            this.$emit('dataChange', res, this.tableData)
        },
        changeloading(data: boolean) {
            this.$emit('loadingData', data)
        },
        paginationChange() {
            this.getData()
        },
        pageSizeChange(size: number) {
            this.scPageSize = size
            this.getData()
        },
        refresh() {
            (this.$refs.scTable as any).clearSelection()
            this.getData()
        },
        upData(params: Record<string, any>, page = 1) {
            this.currentPage = page
                ; (this.$refs.scTable as any).clearSelection()
            Object.assign(this.tableParams, params || {})
            this.getData()
        },
        reload(params: Record<string, any>, page = 1) {
            this.currentPage = page
            this.tableParams = params || {}
                ; (this.$refs.scTable as any).clearSelection()
                ; (this.$refs.scTable as any).clearSort()
                ; (this.$refs.scTable as any).clearFilter()
            this.getData()
        },
        columnSettingChange(userColumn: ColumnItem[]) {
            this.userColumn = userColumn
            this.toggleIndex += 1
        },
        async columnSettingSave(userColumn: ColumnItem[]) {
            ; (this.$refs.columnSetting as any).isSave = true
            try {
                await config.columnSettingSave(this.tableName, userColumn)
            } catch (error) {
                this.$message.error('保存失败')
                    ; (this.$refs.columnSetting as any).isSave = false
                return
            }
            this.$message.success('保存成功')
                ; (this.$refs.columnSetting as any).isSave = false
        },
        async columnSettingBack() {
            ; (this.$refs.columnSetting as any).isSave = true
            try {
                const column = await config.columnSettingReset(this.tableName, this.column)
                this.userColumn = column
                    ; (this.$refs.columnSetting as any).usercolumn = JSON.parse(JSON.stringify(this.userColumn || []))
            } catch (error) {
                this.$message.error('重置失败')
                    ; (this.$refs.columnSetting as any).isSave = false
                return
            }
            ; (this.$refs.columnSetting as any).isSave = false
        },
        sortChange(obj: SortParams) {
            if (!this.remoteSort) return false

            if (obj.column && obj.prop) {
                this.prop = obj.prop
                this.order = obj.order
            } else {
                this.prop = null
                this.order = null
            }
            this.getData()
        },
        filterHandler(value: any, row: any, column: any): boolean {
            const property = column.property
            return row[property] === value
        },
        filterChange(filters: FilterParams) {
            if (!this.remoteFilter) return false

            Object.keys(filters).forEach((key) => {
                filters[key] = filters[key].join(',')
            })
            this.upData(filters)
        },
        remoteSummaryMethod(param: any): any[] {
            const { columns } = param
            const sums: any[] = []
            columns.forEach((column: any, index: number) => {
                if (index === 0) {
                    sums[index] = '合计'
                    return
                }
                const values = this.summary[column.property]
                sums[index] = values || ''
            })
            return sums
        },
        configSizeChange() {
            (this.$refs.scTable as any).doLayout()
        },
        unshiftRow(row: any) {
            this.tableData.unshift(row)
        },
        pushRow(row: any) {
            this.tableData.push(row)
        },
        updateKey(row: any, rowKey: string = this.rowKey) {
            this.tableData
                .filter((item) => item[rowKey] === row[rowKey])
                .forEach((item) => {
                    Object.assign(item, row)
                })
        },
        updateIndex(row: any, index: number) {
            Object.assign(this.tableData[index], row)
        },
        removeIndex(index: number) {
            this.tableData.splice(index, 1)
        },
        removeIndexes(indexes: number[] = []) {
            indexes.forEach((index) => {
                this.tableData.splice(index, 1)
            })
        },
        removeKey(key: string, rowKey: string = this.rowKey) {
            const index = this.tableData.findIndex((item) => item[rowKey] === key)
            if (index !== -1) {
                this.tableData.splice(index, 1)
            }
        },
        removeKeys(keys: string[] = [], rowKey: string = this.rowKey) {
            keys.forEach((key) => {
                const index = this.tableData.findIndex((item) => item[rowKey] === key)
                if (index !== -1) {
                    this.tableData.splice(index, 1)
                }
            })
        },
        clearSelection() {
            (this.$refs.scTable as any).clearSelection()
        },
        toggleRowSelection(row: any, selected: boolean) {
            (this.$refs.scTable as any).toggleRowSelection(row, selected)
        },
        toggleAllSelection() {
            (this.$refs.scTable as any).toggleAllSelection()
        },
        toggleRowExpansion(row: any, expanded: boolean) {
            (this.$refs.scTable as any).toggleRowExpansion(row, expanded)
        },
        setCurrentRow(row: any) {
            (this.$refs.scTable as any).setCurrentRow(row)
        },
        clearSort() {
            (this.$refs.scTable as any).clearSort()
        },
        clearFilter(columnKey: string) {
            (this.$refs.scTable as any).clearFilter(columnKey)
        },
        doLayout() {
            (this.$refs.scTable as any).doLayout()
        },
        sort(prop: string, order: string) {
            (this.$refs.scTable as any).sort(prop, order)
        }
    }
}
</script>

<style scoped>
.scTable-table {
    height: calc(100% - 50px);
}

.scTable-page {
    height: 50px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 15px;
}

.scTable-do {
    white-space: nowrap;
}

.scTable:deep(.el-table__footer) .cell {
    font-weight: bold;
}

.scTable:deep(.el-table__body-wrapper) .el-scrollbar__bar.is-horizontal {
    height: 12px;
    border-radius: 12px;
}

.scTable:deep(.el-table__body-wrapper) .el-scrollbar__bar.is-vertical {
    width: 12px;
    border-radius: 12px;
}
</style>
